<template>
  <div class="app-container calendar-list-container">
    <div class="apply-query">
      <el-row class="filter-query">
        <el-col><span>{{$t('managementCost.profitSharing.queryCondition')}}</span></el-col>
      </el-row>
      <!--搜索表单-->
      <el-form :inline="true" :model="listQuery" style="padding: 0 20px">
        <el-row style="padding-bottom: 10px">
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">Year</div>
              <dict-select v-model="listQuery.year" code="year" :clearable="true"></dict-select>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">{{$t('managementCost.profitSharing.projectNo')}}</div>
              <el-select v-model="listQuery.projectNo" filterable remote :placeholder="$t('managementCost.profitSharing.enterProjectNo')" :remote-method="getProjectList" :loading="loading" :no-data-text="$t('public.noData')" :loading-text="$t('public.loading')">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.label"></el-option>
              </el-select>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">{{$t('managementCost.profitSharing.projectName')}}</div>
              <el-input v-model="listQuery.projectName" :placeholder="$t('managementCost.profitSharing.enterProjectName')"></el-input>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">Account</div>
              <el-select filterable clearable v-model="listQuery.bu" :placeholder="$t('placeholder.choose')">
                <el-option v-for="item in buList" :key="item.id" :label="item.bu" :value="item.bu"></el-option>
              </el-select>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">{{$t('managementCost.profitSharing.configureTime')}}</div>
              <el-date-picker style="width: 100%" format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss" v-model="listQuery.startDate" type="daterange" range-separator="-" :start-placeholder="$t('placeholder.startDate')" :end-placeholder="$t('placeholder.endDate')"></el-date-picker>
            </div>
          </el-col>
          <el-col :span="4" style="margin-top: 33px">
            <div type="primary" class="yt-btn yt-btn-ys" @click="handleFilter">{{$t('button.query')}}</div>
            <div type="primary" class="yt-btn yt-ml8" @click="reset">{{$t('button.reset')}}</div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="yt-data-list">
      <div class="yt-list-title">
        <span>{{$t('managementCost.profitSharing.projectProfitSharing')}}</span>
      </div>
      <div class="yt-list-content">
        <div class="list-operation">
          <div class="yt-btn yt-btn-ys" type="primary" @click="handleAdd">{{$t('button.new')}}</div>
          <div class="yt-btn yt-ml8" type="danger" @click="handleDelete">{{$t('button.delete')}}</div>
          <!--<div class="yt-btn yt-ml8" type="danger" @click="handlePreserve">{{$t('button.preserve')}}</div>-->
        </div>
        <!--主列表-->
        <el-table :data="list" :empty-text="$t('placeholder.emptyText')"  style="width: 100%;" class="yt-table yt-temporary" @selection-change="handleSelectionChange" max-height="600">
          <el-table-column type="selection" align="center" class-name="pd" prop="id" min-width="60"/>
          <el-table-column type="index" align="center" :label="$t('managementCost.profitSharing.serialNum')" min-width="100"/>
          <el-table-column align="center" label="Year" min-width="60" prop="year" class-name="pd"/>
          <el-table-column align="center" :label="$t('managementCost.profitSharing.projectNo')" prop="projectNo" class-name="pd" min-width="100"/>
          <el-table-column align="center" :label="$t('managementCost.profitSharing.projectName')" prop="projectName" class-name="pd" min-width="250" :show-overflow-tooltip="true"/>
          <el-table-column align="center" label="Account" prop="bu" class-name="pd" min-width="100"/>
          <el-table-column align="center" :label="$t('managementCost.profitSharing.contractIncome')" prop="contractIncome" class-name="pd" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{scope.row.contractIncome}}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('managementCost.profitSharing.contractIncomeAmount')" prop="contractIncomeAmount" class-name="pd" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{scope.row.contractCost}}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('managementCost.profitSharing.contractCosts')" prop="contractCosts" class-name="pd" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{scope.row.pastYearIncome}}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('managementCost.profitSharing.contractCostAmount')" prop="contractCostAmount" class-name="pd" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{scope.row.pastYearCost}}</div>
            </template>
          </el-table-column>
          <!-- <el-table-column align="center" :label="$t('managementCost.profitSharing.recognizedIncome')" prop="recognizedIncome" class-name="pd" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{scope.row.recognizedIncome}}</div>
            </template>
          </el-table-column> -->
          <!-- <el-table-column align="center" :label="$t('managementCost.profitSharing.recognizedCost')" prop="recognizedCost" class-name="pd" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{scope.row.recognizedCost}}</div>
            </template>
          </el-table-column> -->
          <el-table-column align="center" :label="$t('managementCost.profitSharing.operation')" prop="name" class-name="pd" min-width="100">
            <template slot-scope="scope">
              <el-button size="small" type="primary" class="yt-btn-ys" style="padding: 5px 10px;margin: 5px 0;" @click="setUp(scope)">{{$t('managementCost.profitSharing.configure')}}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="listQuery.page"
            :page-sizes="[10, 20, 30, 50, 100, 200]"
            :page-size="listQuery.limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </div>


    <!--占比设置弹窗-->
    <el-dialog
      :title="$t('managementCost.profitSharing.setProjectProfitSharing')"
      :visible.sync="setUpDialog"
      class="yt-dialogForm-box"
      :before-close="setUpCancel"
    >
      <el-row style="margin-bottom: 20px">
        <div class="yt-btn yt-btn-ys" type="primary" @click="dialogAdd">
          {{$t('button.new')}}
        </div>
        <!--删除-->
        <div class="yt-btn yt-ml8" type="danger" @click="dialogDelete">
          {{$t('button.delete')}}
        </div>
      </el-row>
      <el-table :data="setUpList" :empty-text="$t('placeholder.emptyText')" label-width="100px" class="yt-table" @selection-change="dialogSelectionChange">
        <el-table-column type="selection" align="center" prop="id"/>
        <el-table-column type="index" align="center" :label="$t('managementCost.profitSharing.serialNum')"/>
        <el-table-column align="center" label="Account" prop="name" class-name="pd">
          <template slot-scope="scope">
              <el-select filterable clearable @change="((val)=>{setBu(val, scope.row)})" v-model="scope.row.bu" :placeholder="$t('placeholder.choose')">
                <el-option v-for="(item, index) in buList" :key="index" :label="item.bu" :value="item.bu"></el-option>
              </el-select>
          </template>
        </el-table-column>
        <el-table-column label="以前年度認列收入" prop="sharePastYearIncome" align="center">
          <template slot-scope="scope">
            <div v-check-submit tabindex="0">
              <el-input style="display: none" type="number" size="small" v-model="scope.row.sharePastYearIncome" :placeholder="$t('placeholder.content')"></el-input>
              <div v-format="'#,##0'" class="box" :placeholder="$t('placeholder.content')">{{scope.row.sharePastYearIncome}}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="以前年度認列成本" prop="sharePastYearCost" align="center">
          <template slot-scope="scope">
            <div v-check-submit tabindex="0">
              <el-input style="display: none" type="number" size="small" v-model="scope.row.sharePastYearCost" :placeholder="$t('placeholder.content')"></el-input>
              <div v-format="'#,##0'" class="box" :placeholder="$t('placeholder.content')">{{scope.row.sharePastYearCost}}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="合約收入" prop="shareContractIncome" align="center">
          <template slot-scope="scope">
            <div v-check-submit tabindex="0">
              <el-input style="display: none" type="number" size="small" v-model="scope.row.shareContractIncome" :placeholder="$t('placeholder.content')"></el-input>
              <div v-format="'#,##0'" class="box" :placeholder="$t('placeholder.content')">{{scope.row.shareContractIncome}}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="合約成本" prop="shareContractCost" align="center">
          <template slot-scope="scope">
            <div v-check-submit tabindex="0">
              <el-input style="display: none" type="number" size="small" v-model="scope.row.shareContractCost" :placeholder="$t('placeholder.content')"></el-input>
              <div v-format="'#,##0'" class="box" :placeholder="$t('placeholder.content')">{{scope.row.shareContractCost}}</div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
         <div class="yt-btn yt-ml8" type="danger" @click="setUpCancel">{{$t('button.cancel')}}</div>
         <div class="yt-btn yt-btn-ys" type="primary" @click="setUpPreserve">{{$t('button.preserve')}}</div>
      </span>
    </el-dialog>

    <!--新增弹窗-->
    <el-dialog :title="$t('managementCost.profitSharing.addConfigure')" :visible.sync="dialogVisible" class="yt-dialogForm-box">
      <div style="padding-bottom:20px">
        <el-row>
          <el-col :span="4" style="margin-right: 20px">
            <div class="labelName">Year</div>
            <dict-select v-model="Info.year" code="year" :clearable="true"></dict-select>
          </el-col>
          <el-col :span="4" style="margin-right: 20px">
            <div class="labelName">{{$t('managementCost.profitSharing.projectNo')}}</div>
            <el-select v-model="Info.projectNo" filterable remote :placeholder="$t('managementCost.profitSharing.enterProjectNo')" :remote-method="getProjectList" :loading="loading">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.label"></el-option>
            </el-select>
          </el-col>
          <el-col :span="4" style="margin-right: 20px">
            <div class="labelName">{{$t('managementCost.profitSharing.projectName')}}</div>
            <el-input v-model="Info.projectName" :placeholder="$t('managementCost.profitSharing.enterProjectName')" style="width: 100%"></el-input>
          </el-col>
          <el-col style="margin-top: 23px;text-align: center;">
            <div class="yt-btn yt-btn-ys" @click="dialogFilter">{{$t('button.query')}}</div>
            <div class="yt-btn yt-ml8" @click="dialogReset">{{$t('button.reset')}}</div>
          </el-col>
        </el-row>
      </div>
      <el-table :data="dialogList" :empty-text="$t('placeholder.emptyText')" class="yt-table" border @selection-change="dialogSelectionChange" max-height="500">
        <el-table-column align="center" width="60">
          <template slot-scope="scope">
            <el-radio v-model="radio" :label="scope.row.id"></el-radio>
          </template>
        </el-table-column>
        <el-table-column type="index" align="center" :label="$t('managementCost.profitSharing.serialNum')" width="60"/>
        <el-table-column label="Project No." prop="projectNo" align="center" min-width="100"/>
        <el-table-column label="Project Name" prop="projectName" align="center" min-width="250" :show-overflow-tooltip="true"/>
        <el-table-column :label="$t('managementCost.profitSharing.departmentNo')" prop="departmentNo" align="center" min-width="100"/>
        <el-table-column label="Category" prop="bu" align="center" min-width="100"/>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <div class="yt-btn yt-btn-ys" type="primary" @click="addPreserve">{{$t('button.choose')}}</div>
        <div class="yt-btn yt-ml8" type="danger" @click="addCancel">{{$t('button.cancel')}}</div>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { queryProject } from '@/api/scheduleManager/worksDetails';
  import { selectBuAndBg } from '@/api/bu/index';
  import { page } from '@/api/project/index';
  import { queryList, putObj, delObj, profitShare, proportion } from '@/api/pmoReport/managementCost';
  import dictSelect from '@/components/Dict/dictValueSelect';

  export default {
    name: 'dailyManagement',
    components: {
      dictSelect,
      'dict-select': () => import('@/components/Dict/dictValueSelect')
    },
    data() {
      return {
        radio: '',
        listQuery: {
          year: '',
          page: 1,
          limit: 10,
          projectNo: '',
          projectName: '',
          startDate: []
        },
        total: 0,
        list: [],
        selectionList: [],
        // 设置
        setUpList: [],
        setUpDialog: false,
        // 新增
        Info: {
          projectNo: '',
          projectName: '',
          year: ''
        },
        dialogList: [], // 新增弹窗数据列表
        dialogVisible: false,
        projectNo: [], // 专案编号
        loading: false,
        projectList: [],
        buList: [],
        options: [],
        currentIndex: 0,
        dialogSelectionList: [],
        projectProfitShare: {}
      };
    },
    created() {
      this.getQuery();
      this.getBu();
      this.getList();
      this.getDialogList()
    },
    methods: {
      setBu(val, row) {
        for (let i = 0; i < this.buList.length; i++) {
          if (this.buList[i].bu === val) {
            row.shareBuId = this.buList[i].id;
            row.bu = this.buList[i].bu;
            break;
          }
        }
      },
      getQuery() {
        const profitSharingListQuery = window.sessionStorage.getItem('profitSharingListQuery');
        if (profitSharingListQuery) {
          this.listQuery = JSON.parse(profitSharingListQuery);
        }
      },
      handlePreserve() {
        // 保存
        if (this.selectionList.length <= 0) {
          this.$notify({
            title: this.$t('tips.fail'),
            message: this.$t('tips.pleaseChoose'),
            type: 'warning'
          });
          return;
        }
        const list = []
        this.selectionList.forEach(item => {
          const arr = []
          item.projectProfitRationList.forEach(doc => {
            arr.push({ bu: doc.bu, proportion: doc.proportion, buId: doc.buId })
          })
          list.push({
            projectId: item.projectId,
            projectNo: item.projectNo,
            projectProfitRationList: arr,
            id: item.id
          })
        })
        this.listLoading = true;
        putObj(list).then(res => {
          this.listLoading = false;
          this.$notify({
            title: res.status === 200 ? this.$t('tips.success') : this.$t('tips.fail'),
            message: res.data,
            type: res.status === 200 ? 'success' : 'warning'
          });
          this.getList();
        });
      },
      dialogAdd() {
        const obj = {
          id: (new Date()).valueOf(),
          shareBuId: '',
          bu: '',
          profitShareId: 0,
          sharePastYearIncome: 0,
          sharePastYearCost: 0,
          shareContractIncome: 0,
          shareContractCost: 0
        }
        this.setUpList.push(obj)
      },
      dialogDelete() {
        const list = this.setUpList.filter(item => !this.dialogSelectionList.some(ele => ele.id === item.id));
        this.setUpList = list
      },
      setUp(scope) {
        this.projectProfitShare = JSON.parse(JSON.stringify(scope.row))
        console.log(this.projectProfitShare)
        // 设置
        // this.setUpList = JSON.parse(JSON.stringify(scope.row.projectProfitRationList))
        if (!this.projectProfitShare.projectProfitProportions || this.projectProfitShare.projectProfitProportions.length === 0) {
          this.projectProfitShare.projectProfitProportions = []
          /* this.projectProfitShare.projectProfitProportions.push(
            {
              shareBuId: scope.row.buId,
              bu: scope.row.bu,
              profitShareId: scope.row.id,
              sharePastYearIncome: scope.row.pastYearIncome,
              sharePastYearCost: scope.row.pastYearCost,
              shareContractIncome: scope.row.contractIncome,
              shareContractCost: scope.row.contractCost
            }
          ) */
        }
        this.setUpList = this.projectProfitShare.projectProfitProportions
        this.currentIndex = scope.$index
        this.setUpDialog = true
      },
      addCancel() {
        this.Info = {
          projectNo: '',
          projectName: ''
        }
        this.dialogVisible = false
      },
      setUpCancel() {
        // 取消
        this.projectProfitShare = {}
        this.setUpList = []
        this.setUpDialog = false
      },
      setUpPreserve() {
        // 设置 保存
        // 1.bu不能重复
        const buArr = []
        this.setUpList.forEach(v => {
          if (!v.bu) {
            this.$message.error('Category不能为空')
            return
          } else {
            buArr.push(v.bu)
          }
        })
        if (new Set(buArr).size !== this.setUpList.length) {
          this.$message.error('Category不能重复')
          return
        }
        // 2.总和不能超过 列表中的值 this.projectProfitShare，this.setUpList
        let sharePastYearIncome = 0
        let sharePastYearCost = 0
        let shareContractIncome = 0
        let shareContractCost = 0
        this.setUpList.forEach(v => {
          sharePastYearIncome += v.sharePastYearIncome * 1
          sharePastYearCost += v.sharePastYearCost * 1
          shareContractIncome += v.shareContractIncome * 1
          shareContractCost += v.shareContractCost * 1
        })
        console.log(sharePastYearIncome)
        console.log(sharePastYearCost)
        console.log(shareContractIncome)
        console.log(shareContractCost)
        if (sharePastYearIncome > this.projectProfitShare.pastYearIncome) {
          this.$message.error('不能超过总以前年度認列收入')
          return
        }
        if (sharePastYearCost > this.projectProfitShare.pastYearCost) {
          this.$message.error('不能超过总以前年度認列成本')
          return
        }
        if (shareContractIncome > this.projectProfitShare.contractIncome) {
          this.$message.error('不能超过总合約收入')
          return
        }
        if (shareContractCost > this.projectProfitShare.contractCost) {
          this.$message.error('不能超过总合約成本')
          return
        }
        console.log(this.setUpList)
        this.$set(this.list[this.currentIndex], 'projectProfitProportions', this.setUpList)
        // 调用接口
        proportion(this.list[this.currentIndex]).then(res => {
          if (res.status === 200) {
            this.setUpList = []
            this.setUpDialog = false
          }
        })
      },
      addPreserve() {
        // 新增弹窗  保存
        if (!this.radio) {
          this.$message.error('请选择专案')
          return false
        }
        if (!this.Info.year) {
          this.$message.error('请选择年度')
          return false
        }
        for (let i = 0; i < this.list.length; i++) {
          if (this.list[i].projectId === this.radio && this.list[i].year === this.Info.year) {
            this.$message.error(this.$t('managementCost.profitSharing.addTip'))
            return false
          }
        }
        /* this.dialogList.forEach(item => {
          if (item.id === this.radio) {
            item.projectProfitRationList = []
            item.projectId = item.id
            item.id = ''
            item.year = this.Info.year
            this.list.push(item)
          }
        }) */
        profitShare({ year: this.Info.year, projectId: this.radio }).then(res => {
          if (res.status === 200) {
            this.reset()
          }
        });
        this.dialogVisible = false
        this.Info = {
          projectNo: '',
          projectName: '',
          year: ''
        }
      },
      getList() {
        this.listLoading = true;
        if (this.listQuery.startDate && this.listQuery.startDate.length > 0) {
          this.listQuery.startTime = this.listQuery.startDate[0];
          this.listQuery.endTime = this.listQuery.startDate[1];
        }
        queryList(this.listQuery).then(response => {
          this.list = response.data.rows;
          this.total = response.data.total;
          this.listLoading = false;
        });
      },
      handleAdd() {
        this.dialogVisible = true
        this.Info = {
          projectNo: '',
          projectName: '',
          year: ''
        }
      },
      dialogSelectionChange(val) {
        this.dialogSelectionList = val;
      },
      handleDelete() {
        if (this.selectionList.length <= 0) {
          this.$notify({
            title: this.$t('tips.fail'),
            message: this.$t('tips.pleaseChoose'),
            type: 'warning'
          });
          return;
        }
        this.$confirm(this.$t('tips.permanentDelete'), this.$t('tips.tips'), {
          confirmButtonText: this.$t('tips.determine'),
          cancelButtonText: this.$t('tips.cancel'),
          type: 'warning'
        }).then(() => {
          const list = this.selectionList.map(item => item.id)
          delObj(list).then(() => {
            this.$notify({
              title: this.$t('tips.success'),
              message: this.$t('tips.deleteSuccess'),
              type: 'success',
              duration: 2000
            });
            this.getList();
          });
        });
      },
      getProjectList(query) {
        // 查询专案编号
        this.loading = true;
        queryProject({ projectNo: query }).then(res => {
          this.loading = false;
          this.options = res.data.rows.map(item => ({ value: item.id, label: item.projectNo }));
        });
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        this.getList();
      },
      handleSelectionChange(val) {
        //  表格序号选中函数
        this.selectionList = val;
      },
      handleFilter() {
        this.getList();
      },
      reset() {
        this.listQuery = {
          page: 1,
          limit: 10,
          projectNo: '',
          projectName: '',
          startDate: []
        };
        this.getList();
      },
      dialogFilter() {
        // 查询
        this.getDialogList()
      },
      dialogReset() {
        // 重置
        this.Info = {
          projectNo: '',
          projectName: '',
          year: ''
        }
        this.getDialogList()
      },
      getDialogList() {
        // 获取新增弹窗列表的数据
        page(this.Info).then(response => {
          this.dialogList = response.data.rows
        })
      },
      getBu() {
        // 获取bu下拉选项
        selectBuAndBg().then(res => {
          this.buList = res.data
        });
      }
    },
    beforeDestroy() {
      window.sessionStorage.setItem('profitSharingListQuery', JSON.stringify(this.listQuery))
    }
  };
</script>
<style scoped>
  /deep/ .el-radio__label {
    display: none;
  }
  /deep/  .el-dialog{
    min-width: 900px;
  }
</style>
